package com.nx.platform.es.bean.modle.score;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.common.Strings;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder.FilterFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.index.query.functionscore.WeightBuilder;

import java.util.Collection;
import java.util.Map;

/**
 * @author
 * @since 2016年11月16日
 */
public class ReverseParamNumberTermsFilterHandler implements ScoreFunctionFieldHandler {

    @Override
    public FilterFunctionBuilder handle(ImmutableMap<String, ?> fieldConfig, Map<String, Object> params) {
        String fieldName = MapUtils.getString(fieldConfig, "fieldName");
        Preconditions.checkState(!Strings.isNullOrEmpty(fieldName));
        String paramName = MapUtils.getString(fieldConfig, "paramName");
        Preconditions.checkState(!Strings.isNullOrEmpty(paramName));
        Object paramValues = MapUtils.getObject(params, paramName);
        if (!(paramValues instanceof Collection)) {
            return null;
        }
        Collection<?> numbres = Collection.class.cast(paramValues);
        float weight = MapUtils.getFloatValue(fieldConfig, "weight", 0f);
        if (numbres.isEmpty() || Float.floatToIntBits(weight) == 0) {
            return null;
        }
        WeightBuilder function = ScoreFunctionBuilders.weightFactorFunction(weight);
        QueryBuilder filter;
        if (numbres.size() == 1) {
            filter = QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery(fieldName, numbres.iterator().next()));
        } else {
            filter = QueryBuilders.boolQuery().mustNot(QueryBuilders.termsQuery(fieldName, numbres));
        }
        return new FilterFunctionBuilder(filter, function);
    }

}
